package zjut.raymond.witdemo.algorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 滑动平均滤波器，可以让传感器数据更平滑
 * 主要维护一个大小固定的队列，新的数据到来时，队首出队，队尾再入队，以队列的平均值作为输出
 */
public class MovingAverageFilter {
    //队列
    private Queue<Double> mQueue;
    //窗口大小
    private int mWindow;
    //队列的总和
    private double sum;
    private double last;

    public MovingAverageFilter(int window) {
        mQueue = new LinkedList<>();
        mWindow = window;
        sum = 0;
    }

    /**
    * 处理数据的方法
     */
    public double filterProcess(double d) {
        last = d;
        if (mQueue.size() >= mWindow) sum -= mQueue.poll();
        mQueue.offer(d);
        sum += d;
        return sum / mQueue.size();
    }

    public double get() {
        return sum / mQueue.size();
    }

    public int size() {
        return mQueue.size();
    }

    public double peek() {
        return mQueue.peek();
    }

    public double getLast() {
        return last;
    }
}
